from odoo import api, models, fields
import logging

_logger = logging.getLogger(__name__)


class PurchaseOrder(models.Model):
    _name = 'purchase.order'
    _inherit = ['purchase.order', 's.mes.upload']

    def _check_to_wms(self, picking):
        """检查 PP、板料、油墨、干膜 """
        for move in picking.move_ids:
            if move.product_id.categ_id.code in ['BS', 'CR', 'DF', 'IK']:
                return True
            if move.product_id.categ_id.parent_id and move.product_id.categ_id.parent_id.code in ['BS', 'CR', 'DF', 'IK']:
                return True
        return False

    def button_confirm(self):
        res = super().button_confirm()
        if self.s_check_allow():
            if self.picking_ids:
                self.wms_post_async()
        return res

    def wms_post_async(self):
        """WMS,采购入库通知单"""
        infos = []
        for pick in self.picking_ids.filtered(lambda x: x.state not in ['done', 'cancel']):
            if not self._check_to_wms(pick): continue
            vals = {"reqTime": fields.Datetime.to_string(fields.Datetime.now()), 'detailInfos': [], 'PO': pick.name + '-' + str(self.id)}
            for move in pick.move_ids:
                infos.append({
                    "POLine": pick.name + '-' + str(self.id) + '-' + str(move.id),
                    "Type": 0,
                    "POCode": self.name,
                    "MaterialID": move.product_id.default_code,
                    "MaterialName": move.product_id.name,
                    "CompanySName": self.partner_id.name,
                    "MatCount": move.product_uom_qty,
                    "Model": move.product_id.standards if move.product_id.standards else '',
                    "Unit": move.product_id.uom_id.name,
                    "WarehouseID": "PD"
                })
        if infos:
            vals['detailInfos'] = infos
            self.wms_upload_data(vals, '/JehaitWS/JOVETG/PurchaseIn')
